package com.zliblike_platform.service.impl;

import com.zliblike_platform.dto.DownloadHistoryQueryDTO;
import com.zliblike_platform.entity.DownloadHistory;
import com.zliblike_platform.mapper.DownloadHistoryMapper;
import com.zliblike_platform.service.DownloadHistoryService;
import com.zliblike_platform.vo.DownloadHistoryVO;
import com.zliblike_platform.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 下载历史服务实现类
 */
@Service
public class DownloadHistoryServiceImpl implements DownloadHistoryService {

    @Autowired
    private DownloadHistoryMapper downloadHistoryMapper;
    
    @Override
    @Transactional
    public Long createDownloadHistory(DownloadHistory downloadHistory) {
        downloadHistoryMapper.insert(downloadHistory);
        return downloadHistory.getDownloadId();
    }
    
    @Override
    public PageResult<DownloadHistoryVO> getUserDownloadHistory(DownloadHistoryQueryDTO queryDTO) {
        // 计算分页参数
        Integer offset = (queryDTO.getPage() - 1) * queryDTO.getSize();
        
        // 查询总记录数
        Integer total = downloadHistoryMapper.countByUserId(
                queryDTO.getUserId(), 
                queryDTO.getStartDate(), 
                queryDTO.getEndDate());
        
        // 计算总页数
        Integer totalPages = (int) Math.ceil((double) total / queryDTO.getSize());
        
        // 查询记录
        List<DownloadHistoryVO> records = downloadHistoryMapper.selectByUserId(
                queryDTO.getUserId(), 
                queryDTO.getStartDate(), 
                queryDTO.getEndDate(), 
                offset, 
                queryDTO.getSize());
        
        return new PageResult<>(total, totalPages, queryDTO.getPage(), records);
    }
    
    @Override
    @Transactional
    public boolean deleteDownloadHistory(Long downloadId, Long userId) {
        return downloadHistoryMapper.deleteById(downloadId, userId) > 0;
    }
    
    @Override
    @Transactional
    public int batchDeleteDownloadHistory(List<Long> downloadIds, Long userId) {
        if (downloadIds == null || downloadIds.isEmpty()) {
            return 0;
        }
        return downloadHistoryMapper.batchDelete(downloadIds, userId);
    }
    
    @Override
    public int getTodayDownloadCount(Long userId) {
        Integer count = downloadHistoryMapper.countTodayDownloads(userId);
        return count != null ? count : 0;
    }
} 